#!/usr/bin/env bash

# 检查是否以 root 权限运行
if [ "$(id -u)" -ne 0 ]; then
    echo "错误: 此脚本需要 root 权限才能运行"
    echo "请使用 sudo 重新运行此脚本"
    exit 1
fi

CURSOR_VERSION="1.1.3"
CURSOR_FILENAME="Cursor-${CURSOR_VERSION}-x86_64.AppImage"
CURSOR_URL="https://downloads.cursor.com/production/979ba33804ac150108481c14e0b5cb970bda3266/linux/x64/${CURSOR_FILENAME}"
INSTALL_DIR="/opt/Cursor"
ICON_PATH="/usr/share/icons/cursor.png"
DESKTOP_FILE="/usr/share/applications/cursor-cursor.desktop"

# 创建临时目录
TEMP_DIR=$(mktemp -d)
cd "$TEMP_DIR" || exit 1

if [ ! -f "$CURSOR_FILENAME" ]; then
    echo "正在下载 Cursor ${CURSOR_VERSION}..."
    wget -q --show-progress "${CURSOR_URL}" || {
        echo "下载失败，请检查网络连接或 URL 是否有效"
        exit 1
    }
fi

echo "设置可执行权限..."
chmod +x "${CURSOR_FILENAME}" || {
    echo "设置可执行权限失败"
    exit 1
}

echo "解压 AppImage..."
./"${CURSOR_FILENAME}" --appimage-extract > /dev/null || {
    echo "解压 AppImage 失败"
    exit 1
}

echo "安装 Cursor 到 ${INSTALL_DIR}..."
# 如果安装目录已存在，先删除
if [ -d "${INSTALL_DIR}" ]; then
    rm -rf "${INSTALL_DIR}"
fi
mkdir -p "${INSTALL_DIR}"
cp -r squashfs-root/usr/share/cursor/* "${INSTALL_DIR}/" 2>/dev/null || true

# 查找主程序
CURSOR_BIN=$(find squashfs-root -type f -executable -name "cursor" | head -n 1)
if [ -n "$CURSOR_BIN" ]; then
    cp "$CURSOR_BIN" "${INSTALL_DIR}/cursor"
else
    echo "警告: 未找到可执行文件 cursor"
fi

# 安装图标
ICON_SRC=$(find squashfs-root -name "cursor.png" | head -n 1)
if [ -n "$ICON_SRC" ]; then
    echo "安装图标..."
    cp "$ICON_SRC" "${ICON_PATH}" || echo "警告: 无法复制图标文件"
else
    echo "警告: 未找到图标文件"
fi

# 安装 desktop 文件
DESKTOP_SRC=$(find squashfs-root -name "cursor-cursor.desktop" | head -n 1)
if [ -n "$DESKTOP_SRC" ]; then
    echo "安装桌面快捷方式..."
    cp "$DESKTOP_SRC" "${DESKTOP_FILE}" || echo "警告: 无法创建桌面快捷方式"
    update-desktop-database 2>/dev/null || echo "警告: 无法更新桌面数据库"
else
    echo "警告: 未找到 desktop 文件"
fi

# 创建命令行启动链接
echo "创建命令行启动链接..."
ln -sf "${INSTALL_DIR}/cursor" /usr/local/bin/cursor || echo "警告: 无法创建命令行链接"

# 清理临时文件
cd /
rm -rf "$TEMP_DIR"

echo "Cursor ${CURSOR_VERSION} 安装完成！"
echo "您可以从应用程序菜单或通过命令行输入 'cursor' 来启动它"